package com.mlan.userap.fragment;


import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.mlan.userap.AppConfig;
import com.mlan.userap.LoginActivity;
import com.mlan.userap.MainActivity;
import com.mlan.userap.MyAPP;
import com.mlan.userap.R;
import com.mlan.userap.SplashActivity;
import com.mlan.userap.activity.ChatActivity;
import com.mlan.userap.adapter.ChatAdapter;
import com.mlan.userap.comm.DividerItemDecoration;
import com.mlan.userap.model.ChatEntry;
import com.mlan.userap.model.ChatGroupInfo;
import com.mlan.userap.model.MsgEvent;
import com.mlan.userap.model.MsgResp;
import com.mlan.userap.model.OpCode;
import com.mlan.userap.okhttp.ApiResponse;
import com.mlan.userap.okhttp.JsonCallBack;
import com.mlan.userap.okhttp.JsonCallBackData;
import com.mlan.userap.okhttp.OkHttpHelper;
import com.mlan.userap.okhttp.RequestBuilder;
import com.mlan.userap.okhttp.model.LoginResponse;
import com.mlan.userap.untils.ConfigManager;
import com.mlan.userap.untils.Convert;
import com.mlan.userap.untils.LogHelper;
import com.mlan.userap.untils.WebSocketManager;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ChatFragment extends BaseFragment  implements ChatAdapter.OnItemClickListener {

    private static ChatFragment instance;
    private RecyclerView rvChatList;
    private ChatAdapter chatAdapter;
    private List<ChatGroupInfo> chatEntries;

    private Map<String, ChatGroupInfo> chatEntryMap;
    private String Tag="ChatFragment";
    // 单例模式，确保 Fragment 不重复创建
    public static ChatFragment getInstance() {
        if (instance == null) {
            instance = new ChatFragment();
        }
        return instance;
    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 确保 Fragment 状态保存
        setRetainInstance(true);
        chatEntryMap = new HashMap<>();
        LoadList();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

       // webSocketManager.removeListener(webSocketListener);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void msgEvent(MsgEvent event) {
        if(event.code.equals(OpCode.Chat.toString())){
            updateChatEntry((MsgResp)event.data);

        }
    }

    private void LoadList(){
        OkHttpHelper.getData("/Chat/GroupList",new JsonCallBackData<List<ChatGroupInfo>>() {
                    @Override
                    public void onSuccess(List<ChatGroupInfo> data) {
                       if(data!=null) updateMultipleData(data);
                    }
                    @Override
                    public void onError(Exception error) {
                    }
                });
    }


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_chat, container, false);

        // 初始化RecyclerView
        rvChatList = view.findViewById(R.id.rv_chat_list);
        rvChatList.setLayoutManager(new LinearLayoutManager(getContext()));

        // 初始化数据（仅在第一次创建时加载）
        if (chatEntries == null) {
            chatEntries = new ArrayList<>();
        }

        // 设置适配器
        chatAdapter = new ChatAdapter(chatEntries);
        rvChatList.setAdapter(chatAdapter);
        chatAdapter.setOnItemClickListener(this);
        chatAdapter.setLongClickListener(new ChatAdapter.OnItemLongClickListener() {
            @Override
            public void onItemLongClick(ChatGroupInfo chatGroupInfo, View v, ChatAdapter.ViewHolder holder) {
                // 获取长按位置
                Float touchX = (Float) v.getTag(R.id.tag_touch_x);
                Float touchY = (Float) v.getTag(R.id.tag_touch_y);
                if (touchX != null && touchY != null) {
                    showCustomPopupMenu(v, holder.getAdapterPosition(), touchX, touchY);
                } else {
                    // 如果没有获取到坐标，使用默认位置
                    showCustomPopupMenu(v, holder.getAdapterPosition(), v.getX(), v.getY());
                }
            }
        });

        // 添加分隔线
        rvChatList.addItemDecoration(new DividerItemDecoration(getContext()));

        // 初始化按钮
        ImageButton btnSearch = view.findViewById(R.id.btn_search);
        ImageButton btnAdd = view.findViewById(R.id.btn_add);

        // 搜索按钮点击
        btnSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getContext(), "Search clicked", Toast.LENGTH_SHORT).show();
            }
        });

        // 添加按钮点击
        btnAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getContext(), "Add clicked", Toast.LENGTH_SHORT).show();
            }
        });

        return view;
    }

    private void showCustomPopupMenu(View anchor, int position, float x, float y) {
        ChatGroupInfo entry = chatEntries.get(position);
        android.widget.PopupWindow popupWindow = new android.widget.PopupWindow(anchor.getContext());
        LinearLayout layout = new LinearLayout(anchor.getContext());
        layout.setOrientation(LinearLayout.VERTICAL);
        layout.setBackgroundColor(0xFFFFFFFF);
        layout.setPadding(16, 8, 16, 8);
        layout.setElevation(4);

        TextView pinOption = new TextView(anchor.getContext());
        pinOption.setText(entry.getTopSequ() > 0 ? "取消置顶" : "置顶");
        pinOption.setTextColor(0xFF000000);
        pinOption.setTextSize(16);
        pinOption.setPadding(0, 8, 0, 8);
        pinOption.setOnClickListener(v -> {
            setTop(position);
            popupWindow.dismiss();
        });

        TextView dndOption = new TextView(anchor.getContext());
        dndOption.setText("免打扰");
        dndOption.setTextColor(0xFF000000);
        dndOption.setTextSize(16);
        dndOption.setPadding(0, 8, 0, 8);
        dndOption.setOnClickListener(v -> {
            //  entry.setDnd(!entry.isDnd());
            popupWindow.dismiss();
        });

        layout.addView(pinOption);
        layout.addView(dndOption);

        popupWindow.setContentView(layout);
        popupWindow.setWidth(200);
        popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setFocusable(true);
        popupWindow.setBackgroundDrawable(new ColorDrawable(0xFFFFFFFF));
        popupWindow.setElevation(4);
        // 从长按位置弹出
        popupWindow.showAtLocation(anchor, android.view.Gravity.NO_GRAVITY, (int) x - 100, (int) y);
    }

    private void updateChatEntry(MsgResp msgResp) {
        ChatGroupInfo entry = chatEntryMap.get(msgResp.getGroupId());
        if (entry != null) {
            int oldPosition = chatEntries.indexOf(entry);
            // 更新最后消息、未读消息数量、时间和 msgTicks
            entry.setLastMsg(msgResp);
            if(!msgResp.getGroupId().equals(AppConfig.groupId)){
                entry.setUnread(entry.getUnread() + 1);
            }

            entry.setMsgTicks(msgResp.getMsgTicks());
            Collections.sort(chatEntries);
            int newPosition = chatEntries.indexOf(entry);
            if (oldPosition != newPosition) {
                chatAdapter.notifyItemMoved(oldPosition, newPosition);
            }
            chatAdapter.notifyItemChanged(newPosition);
        }


//        else {
//
//            chatEntries.add(msgResp);
//            chatEntryMap.put(msgResp.getGroupId(), newEntry);
//            chatAdapter.addItem(newEntry);
//        }
    }

    // 更新多条数据
    public void updateMultipleData(List<ChatGroupInfo> newData) {
        chatEntries.clear();
        chatEntryMap.clear();
        chatEntries.addAll(newData);
        for (ChatGroupInfo entry : chatEntries) {
            chatEntryMap.put(entry.getGroupId(), entry);
        }
        chatAdapter.notifyDataSetChanged(); // 刷新整个列表
    }

    // 更新单条数据
    public void updateSingleData(int position, ChatGroupInfo newEntry) {
        if (position >= 0 && position < chatEntries.size()) {
            chatEntries.set(position, newEntry);
            chatEntryMap.put(newEntry.getGroupId(), newEntry);
            chatAdapter.notifyItemChanged(position);
        }
    }
    @Override
    public void onItemClick(ChatGroupInfo chatEntry) {
        // 处理点击事件，例如显示 Toast 或跳转到详情页面
        Intent intent = new Intent(getContext(), ChatActivity.class);
        intent.putExtra("groupInfo", Convert.toJson(chatEntry,ChatGroupInfo.class));
        startActivity(intent);

        int position = chatEntries.indexOf(chatEntry);
        chatEntry.setUnread(0);
        chatAdapter.notifyItemChanged(position);
    }

    private void showSetTopDialog(int position) {
        new AlertDialog.Builder(requireContext())
                .setTitle("设置置顶")
                .setMessage("是否将该聊天置顶？")
                .setPositiveButton("确定", (dialog, which) -> {
                    setTop(position);
                })
                .setNegativeButton("取消", null)
                .show();
    }

    private void setTop(int pos) {
        ChatGroupInfo entry = chatEntries.get(pos);
        Map<String, String> map = new HashMap<>();
        map.put("groupId", chatAdapter.getGroupId(pos));
        // 根据topSequ判断：大于0表示已置顶，需要取消置顶；否则需要置顶
        map.put("sequ", entry.getTopSequ() > 0 ? "0" : "1");
        OkHttpHelper.get("/Chat/SetTopSequ", map, new JsonCallBack<Object>() {
            @Override
            public void onSuccess(ApiResponse<Object> result,String value2) {
                // 刷新列表
                LoadList();
            }

            @Override
            public void onError(Exception error) {
                Toast.makeText(getContext(), "操作失败", Toast.LENGTH_SHORT).show();
            }
        });
    }
}